package online.struts.chain.command;

import java.util.Objects;

import online.filter.FilterUtil;
import online.struts.mapping.RequestMapping;

import org.apache.logging.log4j.LogManager;
import org.apache.struts.chain.commands.ActionCommandBase;
import org.apache.struts.chain.contexts.ActionContext;
import org.apache.struts.chain.contexts.ServletActionContext;
import org.apache.struts.config.ActionConfig;

import core.exception.PhysicalException;
import core.util.ArrayUtil;

/**
 * サーブレットパスプロセッサ
 *
 * @author Tadashi Nakayama
 * @version 1.0.0
 */
public final class ServletPathProcessor extends ActionCommandBase {

	/** ServletPath設定項目名 */
	private String name;
	/** 許可値 */
	private String[] value;

	/**
	 * @return the name
	 */
	public String getName() {
		return this.name;
	}

	/**
	 * @param val the name to set
	 */
	public void setName(final String val) {
		this.name = val;
	}

	/**
	 * @return the value
	 */
	public String getValue() {
		return ArrayUtil.concatenate(",", this.value);
	}

	/**
	 * @param val the value to set
	 */
	public void setValue(final String val) {
		if (!Objects.toString(val, "").isEmpty()) {
			this.value = val.split(",");
		}
	}

	/**
	 * @see org.apache.struts.chain.commands.ActionCommandBase
	 * #execute(org.apache.struts.chain.contexts.ActionContext)
	 */
	@Override
	public boolean execute(final ActionContext context) throws Exception {
		// キャスト
		if (!ServletActionContext.class.isInstance(context)) {
			LogManager.getLogger().error(context);
			throw new IllegalStateException(String.valueOf(context));
		}
		ServletActionContext sac = ServletActionContext.class.cast(context);

		ActionConfig ac = context.getActionConfig();
		if (!RequestMapping.class.isInstance(ac)) {
			return false;
		}
		RequestMapping mapping = RequestMapping.class.cast(ac);

		if (sac.getForwardConfig() != null) {
			return false;
		}

		if (ActionRequest.isException(sac) || !ActionRequest.isFirst(sac, this.getClass())) {
			return false;
		}

		String cpath = sac.getRequest().getContextPath();
		String uri = FilterUtil.getRequestURI(sac.getRequest());
		if (this.value == null || this.value.length == 0) {
			if (uri.startsWith(cpath + mapping.getPath())) {
				return false;
			}
		} else {
			for (final String path : this.value) {
				if (uri.startsWith(cpath + "/" + path + mapping.getPath())) {
					if (this.name != null) {
						sac.getRequest().setAttribute(this.name, path);
					}
					return false;
				}
			}
		}

		throw new PhysicalException("wrong servlet path", null);
	}
}
